package com.rio.volley;

import java.util.Map;

import com.android.volley.NoConnectionError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.rio.core.Api;
import com.rio.core.L;
import com.rio.core.U;

public class MultipartRequestManager {

	/**
	 * 发送一个JSON请求
	 * 
	 * @param api
	 * @param cls
	 * @param event
	 * @return
	 */
	private static <T> MultipartRequest<T> getRequest(Api api,
			MultipartEntity entity, final RequestEvent<T> event) {
		if (U.notNull(api) && U.notNull(event)) {
			String url = api.getRequest();
			return getRequest(url, entity, event);
		}
		return null;
	}

	/**
	 * 发送一个JSON请求
	 * 
	 * @param api
	 * @param cls
	 * @param event
	 * @return
	 */
	private static <T> MultipartRequest<T> getRequest(final String url,
			MultipartEntity entity, final RequestEvent<T> event) {
		event.onPreExecute();
		MultipartRequest<T> request = null;
		L.i(url);
		if (U.notNull(url)) {
			request = new MultipartRequest<T>(Method.POST, url, entity,
					new Response.Listener<T>() {
						@Override
						public void onResponse(T response) {
							event.onSuccess(response);
							event.onPostExecute();
						}
					}, new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError error) {
							event.onFail(error);
							event.onPostExecute();
						}
					}) {

				@Override
				public T executeResponse(String json) throws Exception {
					//L.ii(json);
					return event.doInBackground(json);

				}
			};
		} else {
			event.onFail(new NoConnectionError());
			event.onPostExecute();
		}
		return request;
	}

	/**
	 * 网络连接
	 * 
	 * @param api
	 * @param event
	 */
	public static <T> void connect(Api api, MultipartEntity entity,
			RequestEvent<T> event) {
		MultipartRequest<T> request = getRequest(api, entity, event);
		if (U.notNull(request))
			RequestManager.getInstance().addRequest(request, null);
	}

	/**
	 * 网络连接
	 * 
	 * @param api
	 * @param event
	 */
	public static <T> void connect(Api api, RequestEvent<T> event) {
		connect(api, null, event);
	}

	/**
	 * 网络连接
	 * 
	 * @param api
	 * @param event
	 */
	public static <T> void connect(String url, RequestEvent<T> event) {
		connect(url, null, event);
	}

	/**
	 * 网络连接
	 * 
	 * @param api
	 * @param event
	 */
	public static <T> void connect(String url,MultipartEntity entity,
			RequestEvent<T> event) {
		MultipartRequest<T> request = getRequest(url, entity, event);
		if (U.notNull(request))
			RequestManager.getInstance().addRequest(request, null);
	}
}
